package com.share.order.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.security.utils.SecurityUtils;
import com.share.order.domain.*;
import com.share.order.mapper.OrderBillMapper;
import com.share.order.mapper.OrderInfoMapper;
import com.share.order.service.IOrderInfoService;
import com.share.rule.api.RemoteFeeRuleService;
import com.share.rule.domain.FeeRule;
import com.share.rule.domain.FeeRuleRequestForm;
import com.share.rule.domain.FeeRuleResponseVo;
import com.share.user.api.RemoteUserInfoService;
import com.share.user.api.domain.UserInfo;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/10/23 下午7:16
 */
@Service
@RequiredArgsConstructor
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    private final OrderInfoMapper orderInfoMapper;
    private final RemoteFeeRuleService remoteFeeRuleService;
    private final RemoteUserInfoService remoteUserInfoService;
    private final OrderBillMapper orderBillMapper;

    /**
     * 查询未完成的订单
     *
     * @param userId
     * @return
     */
    @Override
    public OrderInfo getNoFinishOrder(Long userId) {
        //查询用户是否有未支付的订单或者充电中的订单
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .in(OrderInfo::getStatus, "0", "1") // 订单状态：0:充电中 1：未支付 2：已支付
                .orderByDesc(OrderInfo::getId)
                .last("limit 1");

        return orderInfoMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 创建订单
     *
     * @param orderForm
     */
    @Override
    public void saveOrder(SubmitOrderVo orderForm) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(orderForm.getUserId());
        orderInfo.setOrderNo(RandomUtil.randomString(8));
        orderInfo.setPowerBankNo(orderForm.getPowerBankNo());
        orderInfo.setStartTime(new Date());
        orderInfo.setStartStationId(orderForm.getStartStationId());
        orderInfo.setStartStationName(orderForm.getStartStationName());
        orderInfo.setStartCabinetNo(orderForm.getStartCabinetNo());

        //远程调用规则
        R<FeeRule> feeRuleR = remoteFeeRuleService.getFeeRule(orderForm.getFeeRuleId());
        orderInfo.setFeeRuleId(feeRuleR.getData().getId());
        orderInfo.setFeeRule(feeRuleR.getData().getDescription());
        orderInfo.setStatus("0");
        orderInfo.setCreateTime(new Date());
        orderInfo.setCreateBy(SecurityUtils.getUsername());

        //远程调用用户服务
        R<UserInfo> userInfoR = remoteUserInfoService.getUserInfo(orderForm.getUserId());
        orderInfo.setNickname(userInfoR.getData().getNickname());
        orderInfoMapper.insert(orderInfo);
    }

    /**
     * 结束订单
     *
     * @param endOrderVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void endOrder(EndOrderVo endOrderVo) {
        //1.根据充电宝编号+订单状态（充电中）查询是否存在，如果不存在没有订单，直接返回
        //如果存在正在充电的订单，把订单结束
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getPowerBankNo, endOrderVo.getPowerBankNo())
                .eq(OrderInfo::getStatus, "0") //订单状态：0:充电中
                .orderByDesc(OrderInfo::getCreateTime)
                .last("limit 1"));
        System.out.println(orderInfo);
        if (ObjectUtils.isEmpty(orderInfo)) {
            return;
        }

        //2.设置订单相关数据，进行更新
        orderInfo.setEndTime(endOrderVo.getEndTime());
        orderInfo.setEndStationId(endOrderVo.getEndStationId());
        orderInfo.setEndStationName(endOrderVo.getEndStationName());
        orderInfo.setEndCabinetNo(endOrderVo.getEndCabinetNo());

        //包含充电时长 以分钟单位
        int duration = Minutes.minutesBetween(new DateTime(orderInfo.getStartTime()), new DateTime(orderInfo.getEndTime())).getMinutes();
        orderInfo.setDuration(duration);

        //远程调用：规则引擎进行费用计算
        FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
        feeRuleRequestForm.setDuration(duration);
        feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());

        R<FeeRuleResponseVo> feeRuleResponseVoR = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
        FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoR.getData();
        orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
        orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
        orderInfo.setDeductAmount(new BigDecimal("0"));
        if (orderInfo.getRealAmount().subtract(new BigDecimal(0)).doubleValue() == 0) {
            orderInfo.setStatus("2");
        } else {
            orderInfo.setStatus("1");
        }
        orderInfoMapper.updateById(orderInfo);

        //3 插入免费账单数据
        OrderBill freeOrderBill = new OrderBill();
        freeOrderBill.setBillAmount(new BigDecimal("0"));
        freeOrderBill.setBillItem(feeRuleResponseVo.getFreeDescription());
        freeOrderBill.setOrderId(orderInfo.getId());
        orderBillMapper.insert(freeOrderBill);

        //4 插入收费账单数据（超过免费时间账单数据）
        BigDecimal exceedPrice = feeRuleResponseVo.getExceedPrice();
        if (exceedPrice.doubleValue() > 0) {
            OrderBill exceedOrderBill = new OrderBill();
            exceedOrderBill.setBillAmount(exceedPrice);
            exceedOrderBill.setBillItem(feeRuleResponseVo.getExceedDescription());
            exceedOrderBill.setOrderId(orderInfo.getId());
            orderBillMapper.insert(exceedOrderBill);
        }
    }

    /**
     * 获取用户订单分页列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<OrderInfo> selectOrderListByUserId(Long userId) {
        //1 根据用户id查询用户所有订单列表，返回list集合
        List<OrderInfo> list = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getUserId, userId));

        //2 遍历list集合，得到每个orderInfo对象
        for (OrderInfo orderInfo : list) {
            //3 判断订单状态时0（充电中）,实时计算充电时间和金额
            if (Objects.equals(orderInfo.getStatus(), "0")) { //表示充电中
                //计算当前充电宝的使用时间
                //结束时间 - 开始时间 = 使用时间
                DateTime now = new DateTime();
                DateTime startTime = new DateTime(orderInfo.getStartTime());
                int minutes = Minutes.minutesBetween(startTime, now).getMinutes();
                //如果充电时长大于0
                if (minutes > 0) {
                    orderInfo.setDuration(minutes);
                    FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
                    feeRuleRequestForm.setDuration(minutes);
                    feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());
                    R<FeeRuleResponseVo> feeRuleResponseVoR = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
                    FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoR.getData();
                    orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
                    orderInfo.setDeductAmount(new BigDecimal("0"));
                    orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
                } else {
                    orderInfo.setDuration(0);
                    orderInfo.setTotalAmount(new BigDecimal("0"));
                    orderInfo.setDeductAmount(new BigDecimal("0"));
                    orderInfo.setRealAmount(new BigDecimal("0"));
                }
            }
        }
        return list;
    }

    /**
     * 获取订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderInfo getInfo(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new ServiceException("该订单不存在！");
        }

        //判断订单状态是否是充电中 0
        if (Objects.equals(orderInfo.getStatus(), "0")) {
            //计算充电时间
            DateTime now = new DateTime(); //当前时间
            DateTime startTime = new DateTime(orderInfo.getStartTime()); //订单开始时间
            int minutes = Minutes.minutesBetween(startTime, now).getMinutes();
            //判断充电时间是否大于0
            if (minutes > 0) {
                //远程调用规则引擎进行费用计算
                orderInfo.setDuration(minutes);
                FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
                feeRuleRequestForm.setDuration(minutes);
                feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());
                R<FeeRuleResponseVo> feeRuleResponseVoR = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
                FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoR.getData();
                orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
                orderInfo.setDeductAmount(new BigDecimal("0"));
                orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
            } else {
                orderInfo.setDuration(0);
                orderInfo.setTotalAmount(new BigDecimal("0"));
                orderInfo.setDeductAmount(new BigDecimal("0"));
                orderInfo.setRealAmount(new BigDecimal("0"));
            }
        }
        //OrderBill
        List<OrderBill> orderBillList = orderBillMapper
                .selectList(new LambdaQueryWrapper<OrderBill>().eq(OrderBill::getOrderId, orderInfo.getId()));
        orderInfo.setOrderBillList(orderBillList);

        //UserInfoVo
        R<UserInfo> userInfoR = remoteUserInfoService.getUserInfo(orderInfo.getUserId());
        UserInfo userInfo = userInfoR.getData();
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setNickname(userInfo.getNickname());
        userInfoVo.setWxOpenId(userInfo.getWxOpenId());
        userInfoVo.setCreateTime(userInfo.getCreateTime());
        userInfoVo.setLastLoginTime(userInfo.getLastLoginTime());
        orderInfo.setUserInfoVo(userInfoVo);
        return orderInfo;
    }

    /**
     * 根据订单编号获取订单详情
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        return orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
    }

    /**
     * 订单报表
     *
     * @param sql
     * @return
     */
    @Override
    public Map<String, Object> getOrderCount(String sql) {
        //调用mapper方法执行sql语句
        List<Map<String, Object>> list = orderInfoMapper.getOrderCount(sql);

        Map<String, Object> dataMap = new HashMap<>();

        List<Object> dateList = new ArrayList<>();
        List<Object> countList = new ArrayList<>();

        //把List集合遍历，得到每个map
        for (Map<String, Object> map : list) {
            dateList.add(map.get("order_date"));
            countList.add(map.get("order_count"));
        }
        //把两个list结合放到dataMap中，返回
        dataMap.put("dateList", dateList);
        dataMap.put("countList", countList);
        return dataMap;
    }

    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getStatus));
        //未支付
        if ("1".equals(orderInfo.getStatus())) {
            orderInfo.setStatus("2");
            orderInfo.setPayTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}
